package com.example.screenprojection;
import android.util.Log;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class ScreenSocketServer extends WebSocketServer {
private final String TAG = ScreenSocketServer.class.getSimpleName();
private WebSocket mWebSocket;
private ScheduledExecutorService retryExecutor = Executors.newSingleThreadScheduledExecutor();
private boolean isRetrying = false; // 避免重复重试
private InetSocketAddress serverAddress; // 保存服务器地址

public ScreenSocketServer(InetSocketAddress inetSocketAddress) {
  super(inetSocketAddress);
  this.serverAddress = inetSocketAddress;
}

@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
  Log.d(TAG, "onOpen");
  mWebSocket = conn;
}

@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
  Log.d(TAG, "onClose: " + reason);
}

@Override
public void onMessage(WebSocket conn, String message) {
  // 留空逻辑不变
}

@Override
public void onError(WebSocket conn, Exception ex) {
  Log.d(TAG, "onError: " + ex.toString());
  // 进入重试逻辑
  if (!isRetrying) {
    isRetrying = true;
    retryConnection();
  }
}

@Override
public void onStart() {
  Log.d(TAG, "onStart");
}

public void sendData(byte[] bytes) {
  if (mWebSocket != null && mWebSocket.isOpen()) {
    mWebSocket.send(bytes);
  }
}

public void close() {
  try {
    stopRetrying(); // 停止重试
    stop(); // 停止服务器
    Log.d(TAG, "Server stopped successfully.");
  } catch (Exception e) {
    Log.d(TAG, "Error stopping server: " + e.getMessage());
  }
}

// 重试逻辑
private void retryConnection() {
  retryExecutor.schedule(() -> {
    try {
      Log.d(TAG, "Attempting to restart server...");

      // 确保当前服务器已停止
      stop();

      // 等待端口释放
      Thread.sleep(2000); // 等待2秒确保端口完全释放

      // 创建新实例并启动
      ScreenSocketServer newServer = new ScreenSocketServer(serverAddress);
      newServer.start();

      Log.d(TAG, "Server restarted successfully.");
      isRetrying = false; // 重置重试状态
      retryExecutor.shutdown(); // 关闭重试线程池
      close();
    } catch (Exception e) {
      Log.d(TAG, "Retry failed: " + e.getMessage());
    }
  }, 5, TimeUnit.SECONDS); // 延迟5秒后进行重试
}

private void stopRetrying() {
  if (!retryExecutor.isShutdown()) {
    retryExecutor.shutdownNow();
  }
  isRetrying = false;
}
}
